const fs = require('fs')
const path = require('path')
const xml2js = require('xml2js')
const request = require('request')
const payUtil = require('./payUtil')
const { readFileSync } = require('fs');
/**
 * 微信-企业付款到零钱
 * 
 * 注意的点是，企业付款到零钱，用的是公众号下的用户openid，所以appid要填成公众号的，保持一致，不能填小程序的
 */
exports.transfers = async (map) => {
    let mapInfo = {}
    // 商户appid
    // 这里的商户appid是公众号appid
    mapInfo.mch_appid = 'wx5d641fc847bb8ed4'
    // 商户id
    mapInfo.mchid = '1600766491'
    // 商户密钥
    mapInfo.mchkey = 'xrXR1234567891234567891234567891'
    // 随机字符串
    mapInfo.nonce_str = payUtil.getRnd32()
    // 商户内部流水号
    mapInfo.partner_trade_no = map.recordId
    // 用户的openid
    mapInfo.openid = map.openid
    // 是否需要校验名字
    mapInfo.check_name = 'NO_CHECK'
    // 金额，单为是分
    mapInfo.amount = map.amount * 100
    // 描述
    mapInfo.desc = '企业付款到零钱'
    // ip，该IP同在商户平台设置的IP白名单中的IP没有关联，该IP可传用户端或者服务端的IP。
    mapInfo.spbill_create_ip = map.ip; // 支持IPV4和IPV6两种格式的IP地址。调用微信支付API的机器IP
    // 签名
    let sign = payUtil.transfersSign(mapInfo)

    // 拼接xm字符串
    let formData = "<xml>";
    formData += "<mch_appid>" + mapInfo.mch_appid + "</mch_appid>";
    formData += "<mchid>" + mapInfo.mchid + "</mchid>";
    formData += "<nonce_str>" + mapInfo.nonce_str + "</nonce_str>";
    formData += "<partner_trade_no>" + mapInfo.partner_trade_no + "</partner_trade_no>";
    formData += "<openid>" + mapInfo.openid + "</openid>";
    formData += "<check_name>" + mapInfo.check_name + "</check_name>";
    formData += "<amount>" + mapInfo.amount + "</amount>";
    formData += "<desc>" + mapInfo.desc + "</desc>";
    formData += "<spbill_create_ip>" + mapInfo.spbill_create_ip + "</spbill_create_ip>";
    formData += "<sign>" + sign + "</sign>";
    formData += "</xml>";
    //console.log(formData)

    const merchantPrivateKeyFilePath = 'controllers/wx/file/apiclient_key.pem';
    const merchantPrivateKeyInstance = readFileSync(merchantPrivateKeyFilePath);

    // 从本地文件中加载「微信支付平台证书」，用来验证微信支付请求响应体的签名
    const platformCertificateFilePath = 'controllers/wx/file/apiclient_cert.pem';
    const platformCertificateInstance = readFileSync(platformCertificateFilePath);

    // 请求路径
    let url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers'
    return new Promise((resolve, reject) => {
        request({
            url: url,
            // 需要证书
            agentOptions: {
                cert: platformCertificateInstance,
                key: merchantPrivateKeyInstance
            },
            method: 'post',
            body: formData,
        }, function (err, response, body) {
            if (!err && response.statusCode == 200) {

                // 创建一个解析xml的对象
                let parser = new xml2js.Parser({
                    trim: true,
                    explicitArray: false,
                    explicitRoot: false
                });

                //解析签名结果xml转json
                parser.parseString(body, (err, res) => {
                   // console.log(res)
                    let result = {}

                    // 判断return_code 为fail的时候，的错误信息
                    if (res.return_code == 'FAIL') {
                        result.msg = res.return_msg
                        reject(result)
                    }

                    // return_code是success 的话， 只代表业务已受理， 并不代表已成功
                    // result_code是success 的话, 才算是付款成功， fail的话，返回错误信息
                    if (res.return_code == 'SUCCESS' && res.result_code == 'FAIL') {
                        result.msg = res.err_code_des
                        reject(result)
                    } else {
                        result.msg = ''
                        resolve(result)
                    }
                })
            }
            reject(err)
        })
    })
}